import numpy as np
import matplotlib.pyplot as plt
from pyswarm import pso

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用黑体
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题


# 定义目标函数（示例：利润计算）
def objective_function(x, uncertainty_factor=0):
    # 假设 x[0] 为作物产量，x[1] 为成本
    yield_per_hectare = x[0]  # 每公顷的产量
    cost_per_hectare = x[1]  # 每公顷的成本
    price_per_unit = 100  # 假设市场价格是100元/单位产量
    profit = yield_per_hectare * price_per_unit - cost_per_hectare

    # 引入不确定性因素 (例如市场价格波动)
    profit_with_uncertainty = profit * (1 + uncertainty_factor * np.random.randn())

    return -profit_with_uncertainty  # 因为pso是最小化问题，因此返回负值


# 设定PSO优化的参数
lb = [0, 100]  # 最小值: 产量和成本的下限
ub = [4495153, 5000]  # 最大值: 产量和成本的上限

# 设置不确定性因子的波动程度
uncertainty_factor = 0.1  # 10%的波动

# 记录不同迭代次数下的利润
iterations = 500
profits_with_uncertainty = []
profits_without_uncertainty = []

# 执行粒子群优化
for i in range(1, iterations + 1):
    # 计算考虑不确定性因素的利润
    best_position, _ = pso(objective_function, lb, ub, maxiter=i, swarmsize=30, debug=False, f_ieqcons=None,
                           kwargs={'uncertainty_factor': uncertainty_factor})
    profit_with_uncertainty = -objective_function(best_position, uncertainty_factor)  # 计算最大利润
    profits_with_uncertainty.append(profit_with_uncertainty)

    # 计算不考虑不确定性因素的利润
    best_position_no_uncertainty, _ = pso(objective_function, lb, ub, maxiter=i, swarmsize=30, debug=False,
                                          f_ieqcons=None, kwargs={'uncertainty_factor': 0})
    profit_without_uncertainty = -objective_function(best_position_no_uncertainty, 0)  # 计算最大利润
    profits_without_uncertainty.append(profit_without_uncertainty)

# 绘制利润变化图
plt.figure(figsize=(10, 6))
plt.plot(range(1, iterations + 1), profits_with_uncertainty, label='Profit taking into account uncertainties', color='r', linestyle='-',
         marker='o')
plt.plot(range(1, iterations + 1), profits_without_uncertainty, label='Profit without taking into account uncertainties', color='b',
         linestyle='--', marker='x')

# 设置中文显示
plt.xlabel('The number of iterations', fontsize=12)
plt.ylabel('Profit (RMB)', fontsize=12)
plt.title('The relationship between the number of iterations of the particle swarm optimization algorithm and profit', fontsize=10)
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.savefig('222.png')

# 显示图形
plt.show()
